package com.iqilu.ksd.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.CheckPhoneBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.SmssdkConfig;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2016/10/19.
 */

public class FindPassActivity extends BaseActivity {

    public static String TAG = "FindPassActivity";

    private TextView tvTitle;
    private ImageView btLeft;
    private EditText etTelephone;
    private EditText etVerify;
    private Button btGetverify;
    private Button btSubmit;

    private static String APPKEY = SmssdkConfig.APPKEY;
    private static String APPSECRET = SmssdkConfig.APPSECRET;

    private LigDialog ligDialog;
    public String phone;
    public String code;
    public static int sendSmsStart = 888;
    public static int sendSmsEnd = 889;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_findpass);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();

        SMSSDK.initSDK(this, APPKEY, APPSECRET);
        EventHandler eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {

                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }

        };
        SMSSDK.registerEventHandler(eh);
    }

    private void initView(){
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        btLeft = getView(R.id.bt_left);
        etTelephone = getView(R.id.et_telephone);
        etVerify = getView(R.id.et_verify);
        btGetverify = getView(R.id.bt_getverify);
        btSubmit = getView(R.id.bt_submit);
        tvTitle.setText(R.string.findpass_title);

        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btGetverify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toGetverify();
            }
        });

        btSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toSubmit();
            }
        });
    }

    private void toGetverify() {
        phone = etTelephone.getText().toString();
        if (!matchPhone(phone)) {
            Toast.makeText(this, R.string.login_telephone_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        SMSSDK.getVerificationCode("86", phone);
        new Thread(new Runnable() {
            public int num = 60;

            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    num--;
                    Message msg = new Message();
                    msg.arg1 = num;
                    msg.arg2 = sendSmsStart;
                    if (num <= 0) {
                        msg.arg2 = sendSmsEnd;
                        handler.sendMessage(msg);
                        num = 60;
                        break;
                    } else {
                        handler.sendMessage(msg);
                    }
                }
            }
        }).start();

    }

    private void toSubmit() {
        code = etVerify.getText().toString();
        phone = etTelephone.getText().toString();
        if (!matchPhone(phone)) {
            Toast.makeText(this, R.string.login_telephone_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(this, R.string.register_input_verify, Toast.LENGTH_SHORT).show();
            return;
        }

//        new CheckPhoneThread().execute();
        checkPhone();
    }

    private void checkPhone(){
        String url = Api.URL_CHECKPHONECODE + "?version=2&phone=" + phone + "&code=" + code;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                ligDialog = new LigDialog(FindPassActivity.this, getString(R.string.waiting));
                ligDialog.show();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ligDialog.dismiss();
                Toast.makeText(FindPassActivity.this, R.string.register_verify_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                ligDialog.dismiss();
                CheckPhoneBean result = null;
                result = JSONUtils.requestDetail(response, "data", CheckPhoneBean.class);
                if (result == null) {
                    Toast.makeText(FindPassActivity.this, R.string.register_verify_error, Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(FindPassActivity.this, ResetPassActivity.class);
                intent.putExtra("code", result.getCode());
                intent.putExtra("verifycode", result.getVerifycode());
                startActivity(intent);
                finish();
            }
        });
    }

    // 验证手机号
    public Boolean matchPhone(String phoneNum) {
        if (phoneNum.length() < 11) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher((CharSequence) phoneNum);
        return matcher.matches();
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            if (result == SMSSDK.RESULT_COMPLETE) {
                //短信注册成功后，返回MainActivity,然后提示新好友
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    Toast.makeText(getApplicationContext(), R.string.register_verifycode_send, Toast.LENGTH_SHORT).show();
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {//返回支持发送验证码的国家列表

                }
            } else if (result == sendSmsStart) {
                btGetverify.setEnabled(false);
                btGetverify.setText((getResources().getString(R.string.register_send_sms_again) + event));
            } else if (result == sendSmsEnd) {
                btGetverify.setEnabled(true);
                btGetverify.setText(getResources().getString(R.string.register_send_verify));
            }
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }
}
